import React, { useRef, useState, useEffect } from 'react';
import { List, Divider, Button, Alert, Tree, Input, message } from 'antd';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';
const { TreeNode } = Tree;
const Code = props => {
    return (
        <SyntaxHighlighter language="typescript" style={dark}>
            {props.children || ''}
        </SyntaxHighlighter>
    );
};
const noop = () => { };
export const ListItem = props => {
    const { onComplete = noop, onDelete = noop, isDone = false } = props;
    return (
        <List.Item>
            {isDone ? (
                <span style={{ textDecoration: 'line-through' }}>
                    - {props.children}
                </span>
            ) : (
                <span>- {props.children}</span>
            )}
            <span>
                <CloseOutlined onClick={() => onDelete()} style={{ color: 'red' }} />
                {isDone || (
                    <CheckOutlined
                        onClick={() => onComplete()}
                        style={{ color: 'green' }}
                    />
                )}
            </span>
        </List.Item>
    );
};

const Tip = () => {
    return (
        <div>
            <Divider orientation="left">题目要求</Divider>
            <List>
                <List.Item>
                    - 编写树形组件（可使用第三方组件）展示树形结构数据
                </List.Item>
                <List.Item>- 可以在组件上增加item</List.Item>
                <List.Item>- 可以在组件上删除item</List.Item>
                <List.Item>- 可以编辑item的name值</List.Item>
                <List.Item>- 可以增加item的chilren节点</List.Item>
                <List.Item>- 数据结构如下：</List.Item>
                <Code>
                    {
                        `type TreeNode = {
    id: string;
    name: string;
    children: TreeNode[];
  }
  // 示例
  const root = {
    id: '0001',
    name: 'root', 
    children: [
      {
        id: '0002',
        name: 'a', 
        children: [] 
      },
      {
        id: '0003',
        name: 'b', 
        children: [] 
      }
    ] 
  }
  `}
                </Code>
            </List>
        </div>
    );
};

const Title = ({ title, changeTitle, deleteFn }) => {
    const [isEdit, setIsEdit] = useState(false);
    const inputRef = useRef(null);
    const [inputV, setInputV] = useState(title);
    const [inputAddV, setInputAddV] = useState('');
    const changeEdit = (isBlur) => {
        setIsEdit(!isEdit);
        if (isBlur) {
            changeTitle(inputV);
        }
    };

    // 获取焦点
    useEffect(() => {
        if (isEdit) {
            inputRef.current.focus();
        }
    }, [isEdit]);

    const onChange = (e) => {
        let value = e.target.value;
        setInputV(value);
    };
    return (
        <div>
            {title}
            {
                isEdit ?
                    <Input ref={inputRef} value={inputV} onChange={onChange} onBlur={() => { changeEdit(true); }} /> :
                    <div style={{ textAlign: 'right' }}>
                        <Button onClick={() => { changeEdit(false); }} style={{ marginLeft: 20 }}>修改</Button>
                        <Button onClick={() => { deleteFn(); }}>删除</Button>
                    </div>
            }
        </div>
    );
};

const Tree1 = () => {
    const root = {
        id: '0001',
        name: 'root',
        treeData: [
            {
                id: '0002',
                name: 'a',
                treeData: []
            },
            {
                id: '0003',
                name: 'b',
                treeData: []
            }
        ]
    };
    const [treeData, setTreeData] = useState([root]);
    const [inputChildShow, setInputChildShow] = useState(false);
    const [inputChildV, setInputChildV] = useState('');
    const [inputItemShow, setInputItemShow] = useState(false);
    const [inputItemV, setInputItemV] = useState('');
    const [selectedKeys, setSelectedKeys] = useState([]);
    // 编辑item
    const changeTitle = (value, curKey) => {
        let copyTree = [...treeData];
        const findNode = (nodes) => {
            nodes.some(item => {
                if (item.id === curKey) {
                    item.name = value;
                    setTreeData(copyTree);
                    return true;
                }
                if (item.treeData && item.treeData.length) {
                    findNode(item.treeData);
                }
            });
        };
        findNode(copyTree);
    };

    // 删除item
    const deleteFn = (id) => {
        let copyTree = [...treeData];
        const findNode = (nodes, level) => {
            nodes.some((item, index, arr) => {
                if (item.id === id) {
                    // 如果是根目录且只有一个不允许删除
                    if (arr.length === 1 && arr[0].id === copyTree[0].id) {
                        return message.info('根节点不允许删除');
                    }
                    arr.splice(index, 1);
                    setTreeData(copyTree);
                    return true;
                }
                if (item.treeData && item.treeData.length) {
                    findNode(item.treeData, index);
                }
            });
        };
        findNode(copyTree, 0);
    };
    const loop = (data, level = 0) => {
        return data.map(item => {
            let { name, id, treeData } = item;
            if (treeData && treeData.length) {
                return (
                    <TreeNode level={level} key={id} title={<Title title={name} deleteFn={() => { deleteFn(id); }} changeTitle={(v) => { changeTitle(v, id); }} />}>
                        {loop(treeData, ++level)}
                    </TreeNode>
                );
            }
            return <TreeNode level={level} key={id} title={<Title title={name} deleteFn={() => { deleteFn(id); }} changeTitle={(v) => { changeTitle(v, id); }} />} />;
        });
    };

    const addChild = () => {
        if (!selectedKeys.length) {
            return message.info('请先点中节点才可以添加children节点');
        }
        setInputItemShow(false);
        setInputChildShow(true);
    };
    const addChild2 = () => {
        if (!selectedKeys.length) {
            return message.info('请先点中节点才可以添加兄弟节点');
        }
        setInputChildShow(false);
        setInputItemShow(true);
    };

    const inputChildAdd = () => {
        setInputChildShow(false);
        let copyTree = [...treeData];
        if (!inputChildV) {
            return message.info('空值无法添加');
        }
        const findNode = (nodes) => {
            nodes.some(item => {
                if (item.id === selectedKeys[0]) {
                    if (item.treeData && item.treeData.length) {
                        item.treeData.push({
                            id: new Date().getTime() + '',
                            name: inputChildV
                        });
                    } else {
                        item['treeData'] = [{
                            id: new Date().getTime() + '',
                            name: inputChildV
                        }];
                    }
                    setInputChildV('');
                    setTreeData(copyTree);
                    return true;
                }
                if (item.treeData && item.treeData.length) {
                    findNode(item.treeData);
                }
            });
        };
        findNode(copyTree);
    };

    const inputChildAdd2 = () => {
        setInputItemShow(false);
        let copyTree = [...treeData];
        if (!inputItemV) {
            return message.info('空值无法添加');
        }
        const findNode = (nodes) => {
            nodes.some((item, i, arr) => {
                if (item.id === selectedKeys[0]) {
                    arr.push({
                        id: new Date().getTime() + '',
                        name: inputItemV
                    });
                    setInputItemV('');
                    setTreeData(copyTree);
                    return true;
                }
                if (item.treeData && item.treeData.length) {
                    findNode(item.treeData);
                }
            });
        };
        findNode(copyTree);
    };
    return (
        <div>
            <Alert message={<Tip />} type="info" />
            <div style={{ height: 20 }} />
            <Divider orientation="left">答题区域</Divider>
            <Button onClick={addChild}>添加children（请先选中父节点）</Button>
            <Button onClick={addChild2}>在组件上增加item（请先选中节点）</Button>
            <div>
                {
                    inputChildShow ?
                        <Input value={inputChildV} onChange={(e) => { setInputChildV(e.target.value); }} placeholder="请添加children,失去焦点添加成功" onBlur={inputChildAdd} /> : null
                }
            </div>
            <div>
                {
                    inputItemShow ?
                        <Input value={inputItemV} onChange={(e) => { setInputItemV(e.target.value); }} placeholder="请增加item,失去焦点添加成功" onBlur={inputChildAdd2} /> : null
                }
            </div>
            {
                // TODO
                <Tree
                    selectedKeys={selectedKeys}
                    onSelect={(keys, node) => { setSelectedKeys(keys); console.log(node); }}
                >
                    {
                        loop(treeData)
                    }
                </Tree>
            }
        </div>
    );
};

export default Tree1;